package com.infore.statisticsAndAlarm.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.infore.statisticsAndAlarm.constant.Constants;
import com.infore.statisticsAndAlarm.constant.ResultConstants;
import com.infore.statisticsAndAlarm.entity.FileType;
import com.infore.statisticsAndAlarm.enums.ResultStatus;
import com.infore.statisticsAndAlarm.repository.IFileTypeRepository;
import com.infore.statisticsAndAlarm.service.IFileTypeService;
import com.infore.statisticsAndAlarm.util.ArrayUtils;
import com.infore.statisticsAndAlarm.util.DateUtil;
import com.infore.statisticsAndAlarm.util.MyBeanUtils;
import com.infore.statisticsAndAlarm.util.ResultEntity;

@Service
public class FileTypeServiceImpl implements IFileTypeService {

	@Autowired
	private IFileTypeRepository iFileTypeRepository;

	public ResultEntity queryFileTypeByBase(String knowledgeType) {
		List<FileType> fileTypes = iFileTypeRepository.findByKnowledgeTypeOrderByCreateTimeAsc(knowledgeType);
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(fileTypes);
	}

	public ResultEntity deleteFileTypes(String ids) {
		List<String> idsList = ArrayUtils.stringToList(ids);
		iFileTypeRepository.deleteByFileTypeIdIn(idsList);
		return new ResultEntity(ResultStatus.SUCCESS, Constants.DELETE_SUCCESS);
	}

	public ResultEntity addOrEdit(List<FileType> fileTypes) {
		List<FileType> list = new ArrayList<FileType>();
		for (FileType fileType : fileTypes) {
			// 判断类型的创建时间是否为空
			if (fileType.getCreateTime() == null) {
				fileType.setCreateTime(DateUtil.getSystemTime());
			}
			// 判断id是否为空，不为空则进行编辑
			if (StringUtils.isNotBlank(fileType.getFileTypeId())) {
				FileType oldFileType = iFileTypeRepository.findById(fileType.getFileTypeId()).orElse(null);
				if (oldFileType != null) {
					MyBeanUtils.copyNonNullProperties(fileType, oldFileType);
					fileType = oldFileType;
					list.add(fileType);
				}
			} else {
				list.add(fileType);
			}
		}
		try {
			iFileTypeRepository.saveAll(list);
		} catch (Exception e) {
			return new ResultEntity(ResultStatus.SUCCESS, ResultConstants.EDIT_ERROR);
		}
		return new ResultEntity(ResultStatus.SUCCESS, ResultConstants.EDIT_SUCCESS);
	}

}
